package com.mtiiot.fstcpserver.fastdfs.core;

import java.io.IOException;
import java.lang.reflect.Array;

public class ProtoStructDecoder<T extends StructBase>
{
  public T[] decode(byte[] bs, Class<T> clazz, int fieldsTotalSize)
    throws Exception
  {
    if (bs.length % fieldsTotalSize != 0)
    {
      throw new IOException("byte array length: " + bs.length + " is invalid!");
    }

    int count = bs.length / fieldsTotalSize;

    StructBase[] results = (StructBase[])Array.newInstance(clazz, count);

    int offset = 0;
    for (int i = 0; i < results.length; i++)
    {
      results[i] = ((StructBase)clazz.newInstance());
      results[i].setFields(bs, offset);
      offset += fieldsTotalSize;
    }

    return (T[]) results;
  }
}